import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo1 {
    public static void main(String[] args) throws SQLException {
        //假定数据库中有一个student表(id,name),往里面插入一个数据
        //让用户通过控制台来输入学号和姓名.
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号: ");
        int id = scanner.nextInt();
        System.out.println("请输入姓名: ");
        String name = scanner.next();

        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java14?characterEncoding=utf8&useSSL=false");//向下转型
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("808250");

        //2.建立连接
        Connection connection = dataSource.getConnection();

        //3.构造SQL语句
        String sql = "insert into student values(?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        statement.setString(2, name);

        //4.执行sql语句
        //返回值是这次操作影响了几行
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        //5.释放必要的资源,关闭链接.
        statement.close();
        connection.close();
    }
}
